package com.qingkai.takeawayorders.activity

import android.os.Bundle
import android.util.Log
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableDoubleStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ConstraintLayout
import coil.compose.AsyncImage
import com.qingkai.takeawayorders.R
import com.qingkai.takeawayorders.category.FoodModel
import com.qingkai.takeawayorders.helper.ChangeNumberItemsListener
import com.qingkai.takeawayorders.helper.ManagementCart
import java.util.Locale
import kotlin.math.roundToInt

class CartActivity : BaseActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            CartScreen(onBackClick = { finish() })
        }
    }

    @Preview(showBackground = true)
    @Composable
    fun CartScreenPreview(
        onBackClick: () -> Unit = {}
    ) {
        CartScreen(onBackClick)
    }

    @Composable
    private fun CartScreen(
        onBackClick: () -> Unit = {}
    ) {
        val context = LocalContext.current
        val managementCart = remember { ManagementCart(context) }
        val cartItems = remember { mutableStateOf(managementCart.getListCart()) }
        val tax = remember { mutableDoubleStateOf(0.0) }
        calculatorCart(managementCart, tax)
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp)
        ) {
            Text(
                modifier = Modifier
                    .padding(top = 36.dp)
                    .fillMaxWidth(),
                text = "My Cart",
                fontSize = 25.sp,
                color = colorResource(R.color.orange),
                textAlign = TextAlign.Center,
                fontWeight = FontWeight.Bold
            )
            if (cartItems.value.isEmpty()) {
                Text(
                    text = "Cart Is Empty",
                    modifier = Modifier.align(Alignment.CenterHorizontally)
                )
            } else {
                CartList(
                    cartItems = cartItems.value,
                    managementCart = managementCart,
                    onItemChange = {
                        cartItems.value = managementCart.getListCart()
                        calculatorCart(managementCart, tax)
                    })
                CartSummary(
                    itemTotal = managementCart.getTotalFee(),
                    tax = tax.doubleValue,
                    delivery = 10.0
                )
            }

        }
    }

    @Composable
    fun CartSummary(itemTotal: Double, tax: Double, delivery: Double) {
        Log.i("CartSummary", "itemTotal=${itemTotal}, tax=${tax}, delivery=${delivery}")
        val total = itemTotal + tax + delivery
        Log.i("CartSummary", "total=${total}")
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 16.dp)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 16.dp)
            ) {
                Text(
                    text = "Item Total:",
                    modifier = Modifier.weight(1f),
                    fontWeight = FontWeight.Bold,
                    color = colorResource(R.color.black)
                )
                Text(
                    text = "$" + String.format(Locale.CHINA, "%.2f", itemTotal),
                )
            }
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 16.dp)
            ) {
                Text(
                    text = "Tax:",
                    modifier = Modifier.weight(1f),
                    fontWeight = FontWeight.Bold,
                    color = colorResource(R.color.black)
                )
                Text(text = "$${tax}")
            }
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 16.dp)
            ) {
                Text(
                    text = "Delivery:",
                    modifier = Modifier.weight(1f),
                    fontWeight = FontWeight.Bold,
                    color = colorResource(R.color.black)
                )
                Text(text = "$$delivery")
            }
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(1.dp)
                    .background(colorResource(R.color.black))
                    .padding(top = 32.dp)
            )
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 16.dp)
            ) {
                Text(
                    text = "Total:",
                    modifier = Modifier.weight(1f),
                    fontWeight = FontWeight.Bold,
                    color = colorResource(R.color.black)
                )
                Text(text = "$${"%.2f".format(total)}")
            }

            Button(
                onClick = {},
                shape = RoundedCornerShape(100.dp),
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 16.dp)
                    .height(50.dp),
                colors = ButtonDefaults.buttonColors(
                    backgroundColor = colorResource(R.color.orange)
                ),
            ) {
                Text(
                    text = "Check Out",
                    fontSize = 22.sp,
                    color = Color.White
                )
            }
        }
    }

    @Composable
    fun CartList(
        cartItems: MutableList<FoodModel>,
        managementCart: ManagementCart,
        onItemChange: () -> Unit
    ) {
        LazyColumn(modifier = Modifier.padding(top = 16.dp)) {
            items(cartItems) { item ->
                CartItem(
                    cartItems = cartItems,
                    item = item,
                    managementCart = managementCart,
                    onItemChange = onItemChange
                )
            }
        }
    }

    @Composable
    fun CartItem(
        cartItems: MutableList<FoodModel>,
        item: FoodModel,
        managementCart: ManagementCart,
        onItemChange: () -> Unit
    ) {
        ConstraintLayout(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 8.dp, bottom = 8.dp)
        ) {
            val (pic, titleTxt, feeEachItem, quantity, totalEachItem) = createRefs()
            AsyncImage(
                model = item.picUrl, contentDescription = null,
                modifier = Modifier
                    .size(90.dp)
                    .background(
                        color = colorResource(R.color.grey), shape = RoundedCornerShape(10.dp)
                    )
                    .padding(8.dp)
                    .constrainAs(pic) {
                        top.linkTo(parent.top)
                        start.linkTo(parent.start)
                        bottom.linkTo(parent.bottom)
                    }
            )
            Text(
                text = item.title,
                modifier = Modifier
                    .constrainAs(titleTxt) {
                        top.linkTo(pic.top)
                        start.linkTo(pic.end)
                    }
                    .padding(start = 8.dp, top = 8.dp)
            )
            Log.i("CartItem", "price:${item.price}")
            Text(
                text = "$${item.price}",
                color = colorResource(R.color.orange),
                modifier = Modifier
                    .constrainAs(feeEachItem) {
                        top.linkTo(titleTxt.bottom)
                        start.linkTo(titleTxt.start)
                    }
                    .padding(start = 8.dp, top = 8.dp)
            )
            Text(
                text = "$${"%.2f".format(item.numberInCart * item.price)}",
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold,
                modifier = Modifier
                    .constrainAs(totalEachItem) {
                        start.linkTo(titleTxt.start)
                        bottom.linkTo(pic.bottom)
                    }
                    .padding(start = 8.dp)
            )
            ConstraintLayout(
                modifier = Modifier
                    .width(100.dp)
                    .constrainAs(quantity) {
                        end.linkTo(parent.end)
                        bottom.linkTo(parent.bottom)
                    }
                    .background(colorResource(R.color.grey), shape = RoundedCornerShape(10.dp))
            ) {
                val (plusCartBtn, minusCartBtn, numberItemTxt) = createRefs()
                Log.i("CartSummary", "numberInCart=${item.numberInCart}")
                Text(
                    text = item.numberInCart.toString(),
                    color = Color.Black,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier
                        .constrainAs(numberItemTxt) {
                            end.linkTo(parent.end)
                            start.linkTo(parent.start)
                            top.linkTo(parent.top)
                            bottom.linkTo(parent.bottom)
                        }
                )
                Box(
                    modifier = Modifier
                        .padding(2.dp)
                        .size(28.dp)
                        .background(
                            colorResource(R.color.orange),
                            shape = RoundedCornerShape(10.dp)
                        )
                        .constrainAs(plusCartBtn) {
                            end.linkTo(parent.end)
                            top.linkTo(parent.top)
                            bottom.linkTo(parent.bottom)
                        }
                        .clickable {
                            managementCart.plusItem(
                                cartItems,
                                cartItems.indexOf(item),
                                object : ChangeNumberItemsListener {
                                    override fun onChanged() {
                                        onItemChange()
                                    }
                                })
                        }
                ) {
                    Text(
                        text = "+",
                        color = Color.White,
                        modifier = Modifier
                            .align(Alignment.Center),
                        textAlign = TextAlign.Center
                    )
                }
                Box(
                    modifier = Modifier
                        .padding(2.dp)
                        .size(28.dp)
                        .background(
                            colorResource(R.color.orange),
                            shape = RoundedCornerShape(10.dp)
                        )
                        .constrainAs(minusCartBtn) {
                            start.linkTo(parent.start)
                            top.linkTo(parent.top)
                            bottom.linkTo(parent.bottom)
                        }
                        .clickable {
                            managementCart.minusItem(
                                cartItems,
                                cartItems.indexOf(item),
                                object : ChangeNumberItemsListener {
                                    override fun onChanged() {
                                        onItemChange()
                                    }
                                })
                        }
                ) {
                    Text(
                        text = "-",
                        color = Color.White,
                        modifier = Modifier
                            .align(Alignment.Center),
                        textAlign = TextAlign.Center
                    )
                }

            }
        }
    }
}

fun calculatorCart(managementCart: ManagementCart, tax: MutableState<Double>) {
    val percentTax = 0.02
    tax.value = ((managementCart.getTotalFee() * percentTax) * 100.0).roundToInt() / 100.0
}